//
//  XiugViewController.m
//  zuixin
//
//  Created by QJY on 14-8-22.
//  Copyright (c) 2014年 dingshenwangluokeji. All rights reserved.
//

#import "XiugViewController.h"
#import "NetAccess.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "Header.h"
#import "HgViewController.h"
//#import "LogViewController.h"
@interface XiugViewController ()<UITextFieldDelegate,NSURLConnectionDataDelegate,UIAlertViewDelegate>

@end

@implementation XiugViewController

{
    UITextField *_field;
    UITextField *_field1;
    UITextField *_field2;
    UITextField *_field3;
    NSMutableData *_data;
    UIAlertView *_alertView;
    NSString *_string;
    UIImageView *_imageView;
    MBProgressHUD *pro;
    NSUserDefaults *users;
    NSString*_name;
    NSString*_word;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)match
{
//    pro = [[MBProgressHUD alloc] initWithView:self.view];
//    pro.labelText = @"正在加载中..";
//    pro.mode = MBProgressHUDModeText;
//    [self.view addSubview:pro];
//    [pro showAnimated:YES whileExecutingBlock:^{
//        [NSThread sleepForTimeInterval:2.0];
//    } completionBlock:^{
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"textFieldgg" object:users];
//    }];
    pro=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _field3.text =nil;
    _field1.text =nil;
    _field2.text =nil;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title =@"修改密码";
    self.view.backgroundColor =[UIColor whiteColor];
    [self controllersd];
    [self textfieldld];
    [self addImageView];
}
-(void)textfieldld
{
    _field =[[UITextField alloc]initWithFrame:CGRectMake(20,_imageView.frame.size.height+120, 320-40,35)];
    UILabel*label=[[UILabel alloc ]initWithFrame:CGRectMake(0, 0, 100, 35)];
    label.textColor=[UIColor colorWithWhite:0.76 alpha:1];
    label.text=@"   用户名：";
    [_field addSubview:label];
    
    _field.backgroundColor =[UIColor whiteColor];
    _field.borderStyle = UITextBorderStyleRoundedRect;
    //    _field.placeholder = @"用户名:";
    _field.text=_name;
    _field.textAlignment=1;
    _field.userInteractionEnabled=NO;
    _field.keyboardType=UIKeyboardTypeNumberPad;
    [self.view addSubview:_field];
    
    _field1 =[[UITextField alloc]initWithFrame:CGRectMake(20,_field.frame.origin.y+45, 320-40,35)];
    _field1.borderStyle =UITextBorderStyleRoundedRect;
    _field1 .delegate =self;
    _field1.placeholder = @"原始密码:";
    [self.view addSubview:_field1];
    
    _field2 =[[UITextField alloc]initWithFrame:CGRectMake(20,_field1.frame.origin.y+45, 320-40,35)];
    _field2.delegate =self;
    _field2.borderStyle =UITextBorderStyleRoundedRect;
    _field2.secureTextEntry =YES;
    _field2.placeholder = @"修改密码:";
    [self.view addSubview:_field2];
    
    _field3 =[[UITextField alloc]initWithFrame:CGRectMake(20,_field2.frame.origin.y+45, 320-40,35)];
    _field3.delegate =self;
    _field3.borderStyle =UITextBorderStyleRoundedRect;
    _field3.secureTextEntry =YES;
    _field3.placeholder = @"确认密码:";
    [self.view addSubview:_field3];
    
}

-(void)addImageView
{
    _imageView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"114.png"]];
    _imageView.frame =CGRectMake(115, 20 ,90, 90);
    [self.view addSubview:_imageView];
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
    btn .frame =CGRectMake(20, _field2.frame.size.height+270, 280, 40);
    btn.backgroundColor =[UIColor colorWithRed:0.2f green:0.6f blue:0.9f alpha:1];
    [btn setTitle:@"确定修改" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.layer.cornerRadius =10;
    btn.tag=1001;
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UIButton *btn1 =[UIButton buttonWithType:UIButtonTypeCustom];
    btn1 .frame =CGRectMake(20, btn.frame.size.height+260+60, 280, 40);
    btn1.backgroundColor =[UIColor colorWithRed:0.2f green:0.6f blue:0.9f alpha:1];
    [btn1 setTitle:@"取消修改" forState:UIControlStateNormal];
    [btn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn1.layer.cornerRadius =10;
    btn1.tag=1002;
    [btn1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn1];
    
}
-(void)btnClick:(UIButton*)sender
{
    if (sender.tag==1002) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        NSLog(@"heheh");
        
        NetAccess *net =[NetAccess sharedNetAccess];
        if(![net haveNet])
        {
            [pro removeFromSuperview];
            UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"无网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            
            
            
        }
        else
        {
            NSLog(@"111111%@%@",_field.text,_field1.text);
            if (IOS5) {
                if (!(_field3.text||_field1.text||_field2.text))
                {
                    [pro removeFromSuperview];
                    _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请确保每一项不为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [_alertView show];
                }
                else{
                    if (![_field3.text isEqualToString:[NSString stringWithFormat:@"%@",_field2.text]]) {
                        _field3.text=@"";
                        _field2.text=@"";
                        [pro removeFromSuperview];
                        _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新密码不一致" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        [_alertView show];
                        
                    }
                    else
                    {
                        [self getShuJu];
                    }}
            }
            else
            {
                
                if ([_field3.text isEqualToString:@""]||[_field1.text isEqualToString:@""]||[_field2.text isEqualToString:@""])
                {
                    [pro removeFromSuperview];
                    _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请确保每一项不为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    
                    [_alertView show];
                    
                }
                else
                {
                    if (![_field3.text isEqualToString:[NSString stringWithFormat:@"%@",_field2.text]])
                    {
                        NSLog(@"111%@222%@",_field2.text,_field3.text);
                        _field3.text=@"";
                        _field2.text=@"";
                        [pro removeFromSuperview];
                        _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新密码不一致" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        [_alertView show];
                        
                    }
                    else
                    {
                        [self getShuJu];
                    }
                }
            }}
    }}
-(void)getShuJu
{
    NSString *str=[NSString stringWithFormat:@"http://oemapi2.leehuu.cn/api/client/ResetPassword?userName=%@&Password=%@&newPassword=%@",_field.text,_field1.text, _field2.text];
    NSLog(@"wohao %@   %@   %@",_field.text,_field1.text, _field2.text);
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *html = operation.responseString;//@"{\"retCode\":-1,\"exception\":\"密码错误！\"}";
        NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
        id dict=[NSJSONSerialization  JSONObjectWithData:data options:0 error:nil];
        NSLog(@"获取到的数据为：%@",dict);
        self.excString=[dict objectForKey:@"exception"];
        self.retString=[dict objectForKey:@"retCode"];
        NSLog(@"%@",self.excString);
        NSLog(@"%@",self.retString);
        NSString *message = @"修改成功,请重新登录";
        // 提示框
        //self.retString=@"0";
        if ([self.retString intValue])
        {
            [pro removeFromSuperview];
            message=self.excString;
            _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [_alertView show];
            return;
        }
        else
            //信息正确
        {
            _alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            _alertView.tag=33;
            _alertView.delegate=self;
            [_alertView show];
            //                        [self match];
            //本地存储
            
            //
            [pro removeFromSuperview];
            NSMutableArray *_usert =[NSMutableArray array];
            [_usert removeAllObjects];
            // users =[NSUserDefaults standardUserDefaults];
            NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
            [dict setObject:_field.text forKey:@"username"];
            [dict setObject:_field2.text forKey:@"userword"];
            [_usert addObject:dict];
            [users setObject:_usert forKey:@"newusers1"];
            [users synchronize];
            
            return;
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"发生错误！%@",error);
    }];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
    //[self dismissViewControllerAnimated:YES completion:nil];
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //UIAlertView*alert=(UIAlertView*)[self.view viewWithTag:33 ];
    if (alertView.tag==33) {
        if (buttonIndex==0) {
            [self presentViewController:[HgViewController alloc] animated:YES completion:nil];
        }
    }
}

#pragma mark--网络代理方法
//-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
//{
//    _data =[[NSMutableData alloc]init];
//}
//-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
//{
//    [_data appendData:data];
//}
//-(void)connectionDidFinishLoading:(NSURLConnection *)connection
//{
//    NSLog(@"1111");
//    _string =[[NSString alloc]initWithData:_data encoding:NSUTF8StringEncoding];
//    NSArray *sdk =[_string componentsSeparatedByString:@"|"];
//    NSLog(@"dict ==%d",sdk.count);
//
//    if([_string hasPrefix:@"0|1"])
//    {
//        NSString *message =@"亲！恭喜充值成功哦！";
//        _alertView.message = message;
//        [_alertView show];
//    }
//    else
//    {
//        NSString *message =[sdk objectAtIndex:2];
//        _alertView.message = message;
//        [_alertView show];
//    }
//}
//-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
//{
//    NSString *message =@"亲！网络不给力啊，稍后再试吧..!";
//    _alertView.message = message;
//    [_alertView show];
//}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_field3 resignFirstResponder];
    [_field1 resignFirstResponder];
    [_field2 resignFirstResponder];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
-(void)controllersd
{
    users =[NSUserDefaults standardUserDefaults];
    NSArray *array =[users objectForKey:@"newusers1"];
    NSDictionary *dict =[array objectAtIndex:0];
    
    _name =[dict objectForKey:@"username"];
    _word=[dict objectForKey:@"userword"];
    //    _phoneName=[dict objectForKey:@"usercellphone" ];
    //dicts=[users objectForKey:@"Dic"];
    NSLog(@"qq%@%@",_name,_word);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{   //开始编辑时，整体上移
    //    if (textField.tag==0) {
    //        [self moveView:-20];
    //    }
    //    if (textField.tag==1)
    //    {
    [self moveView:-80];
    //    }
}
-(void)textFieldDidEndEditing:(UITextField *)textField{     //结束编辑时，整体下移
    //    if (textField.tag==0) {
    //        [self moveView:20];
    //    }
    //    if (textField.tag==1)
    //    {
    [self moveView:80];
    //    }
}
-(void)moveView:(float)move{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    frame.origin.y+=move;//view的X轴上移
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];//设置调整界面的动画效果
    
    
}
@end